﻿using GMS.NET.Application.Service.System.Extensions;
using GMS.NET.Application.Service.System.Topics;
using Microsoft.Extensions.Logging;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMS.NET.Application.Service.System.MqttNet
{
    public class MqttSubscriptionService : MqttServerBase, IMqttSubscriptionService
    {
        private readonly ILogger<MqttSubscriptionService> _logger;
        public MqttSubscriptionService(ILogger<MqttSubscriptionService> logger)
        {
            _logger = logger;
        }

        public override void ConfigureMqttServer(MqttServer mqttServer)
        {
            base.ConfigureMqttServer(mqttServer);

            MqttServer.ClientSubscribedTopicAsync += ClientSubscriptedHandlerAsync;
            MqttServer.InterceptingSubscriptionAsync += InterceptingSubscriptionHandlerAsync;
            MqttServer.ClientUnsubscribedTopicAsync += ClientUnsubscribtedTopicHandlerAsync;
            MqttServer.InterceptingUnsubscriptionAsync += InterceptingUnsubscriptionHandlerAsync;
        }

        /// <summary>
        /// 处理客户端订阅
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        private Task ClientSubscriptedHandlerAsync(ClientSubscribedTopicEventArgs eventArgs)
        {
            _logger.LogDebug($"'{eventArgs.ClientId}' subscripted '{eventArgs.TopicFilter.Topic}'");
            return Task.CompletedTask;
        }



        private Task InterceptingSubscriptionHandlerAsync(InterceptingSubscriptionEventArgs eventArgs)
        {
            if (MqttTopicHelper.IsSystemTopic(eventArgs.TopicFilter.Topic) && eventArgs.ClientId != "Administrator")
                eventArgs.Response.ReasonCode = MqttSubscribeReasonCode.ImplementationSpecificError;
            if (eventArgs.TopicFilter.Topic.StartsWith(BrokerTopics.Secret.Base) && eventArgs.ClientId != "Imperators")
            {
                eventArgs.Response.ReasonCode = MqttSubscribeReasonCode.ImplementationSpecificError;
                eventArgs.CloseConnection = true;
            }

            return Task.CompletedTask;
        }


        private Task ClientUnsubscribtedTopicHandlerAsync(ClientUnsubscribedTopicEventArgs eventArgs)
        {
            _logger.LogDebug($"'{eventArgs.ClientId}' unsubscripted topic '{eventArgs.TopicFilter}'");
            return Task.CompletedTask;
        }


        private Task InterceptingUnsubscriptionHandlerAsync(InterceptingUnsubscriptionEventArgs eventArgs)
        {
            _logger.LogDebug($"'{eventArgs.ClientId}' unsubscripted topic '{eventArgs.Topic}'");
            return Task.CompletedTask;
        }
    }
}
